package com.shiroha.video.config;

import feign.Logger;
import feign.Request;
import feign.Response;
import feign.Util;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class FeignCustomLogger extends Logger {
    private final org.slf4j.Logger logger = LoggerFactory.getLogger(FeignCustomLogger.class);

    @Override
    protected void logRequest(String configKey, Level logLevel, Request request) {
        logger.info("Feign Request: {} {}", request.httpMethod(), request.url());
        logger.info("Feign Headers: {}", request.headers());
        if (request.body() != null) {
            logger.info("Feign Body: {}", new String(request.body()));
        }
    }

    @Override
    protected Response logAndRebufferResponse(String configKey, Level logLevel, Response response, long elapsedTime) throws IOException {
        logger.info("Feign Response: {}", response.status());
        logger.info("Feign Headers: {}", response.headers());
        if (response.body() != null) {
            byte[] bodyData = Util.toByteArray(response.body().asInputStream());
            logger.info("Feign Body: {}", new String(bodyData));
            return response.toBuilder().body(bodyData).build();
        }
        return response;
    }

    @Override
    protected void log(String configKey, String format, Object... args) {
        logger.info(String.format(methodTag(configKey) + format, args));
    }
}
